<template>
	<section>
		<!--工具条 - 高级查询框-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="query">
				<el-form-item>
					<el-input v-model="query.keyword" placeholder="请输入关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleOnSale" :disabled="this.sels.length===0">上架</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleOffSale" :disabled="this.sels.length===0">下架</el-button>
        </el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="pageInfo.rows" highlight-current-row v-loading="listLoading" height="650" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55" fixed>
			</el-table-column>
			<el-table-column type="index" width="60" fixed>
			</el-table-column>
			<el-table-column prop="title" label="名称" fixed width="120" sortable>
			</el-table-column>
      <el-table-column prop="cover" label="封面图" width="120" sortable>
        <template slot-scope="scope">
            <img :src="scope.row.cover" width="30px" height="30px">
        </template>
      </el-table-column>
			<el-table-column prop="salePrice" label="原价" width="100" sortable>
			</el-table-column>
			<el-table-column prop="costPrice" label="折扣价" width="100" sortable>
			</el-table-column>
			<el-table-column prop="isNew" label="是否新车" width="100" sortable>
        <template slot-scope="scope">
            <span v-if="scope.isNew == 1">是</span>
            <span v-else>否</span>
        </template>
			</el-table-column>
      <el-table-column prop="registerTime" label="上牌时间" width="100" sortable>
      </el-table-column>
      <el-table-column prop="mileage" label="里程数" width="100" sortable>
      </el-table-column>
      <el-table-column prop="shopName" label="店铺名称" width="100" sortable>
      </el-table-column>
      <el-table-column prop="onSaleTime" label="上架时间" width="100" sortable>
      </el-table-column>
      <el-table-column prop="offSaleTime" label="下架时间" width="100" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" min-width="100" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.state == 1" style="color: blue">上架</span>
          <span v-else>下架</span>
        </template>
      </el-table-column>
      <el-table-column prop="costEffective" label="超值" min-width="100" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.costEffective == 1">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column prop="rushSale" label="急售" min-width="100" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.rushSale == 1">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column prop="quasiNewCar" label="准新车" min-width="100" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.quasiNewCar == 1">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column prop="transitiveCountry" label="可提全国" min-width="100" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.transitiveCountry == 1">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column prop="type.name" label="类型" width="100" sortable>
      </el-table-column>
      <el-table-column prop="brand" label="品牌" width="100" sortable>
      </el-table-column>
      <el-table-column prop="seller.username" label="营销人员" width="100" sortable>
      </el-table-column>
      <el-table-column prop="auditState" label="审核状态" width="100" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.auditState == 1">已审核</span>
          <span v-else>未审核</span>
        </template>
      </el-table-column>
			<el-table-column label="操作" min-width="380" fixed="right">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
					<el-button type="warning" size="small" @click="maintenanceResources(scope.$index, scope.row)">资源维护</el-button>
					<el-button type="info" size="small" @click="handleDel(scope.$index, scope.row)">上传检测报告</el-button>
				</template>
			</el-table-column>
		</el-table>

<!--    车辆资源抽屉框-->
    <el-drawer
        title="车辆资源维护"
        :visible.sync="tableVisible"
        direction="rtl"
        size="50%">
      <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
        <el-button size="small" type="primary" v-on:click="resourceAdd">新增</el-button>
      </el-col>
      <el-table :data="carResourcesList">
          <el-table-column property="id" label="编号" width="150">
          </el-table-column>
          <el-table-column property="resourceUrl" label="资源路径" width="200"></el-table-column>
          <el-table-column property="resourceType" label="资源类型" width="100"></el-table-column>
        <el-table-column label="操作" min-width="100" fixed="right">
          <template scope="scope">
            <el-button type="success" size="small" @click="resourceEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="resourceDel(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>

<!--    资源新增弹框-->
    <el-dialog title="新增/修改" :visible.sync="resourceAddVisible">
      <el-form :model="resourceForm">
        <el-form-item label="资源类型">
          <el-select v-model="resourceForm.resourceTypeName" placeholder="请选择">
            <el-option
                v-for="resource in sourceTree"
                :key="resource.id"
                :label="resource.resourceTypeName"
                :value="resource.resourceTypeName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="资源文件">
          <el-upload
              class="upload-demo"
              action="http://localhost:8081/fastdfs/upload"
              :on-change="resourceHandleChange"
              :on-success="resourceHandleSuccess"
              :before-upload="beforeResourceUpload"
              :on-remove="resourceHandleRemove"
              :file-list="resourceFileList">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resourceAddVisible = false">取 消</el-button>
        <el-button type="primary" @click="resourceSave">确 定</el-button>
      </div>
    </el-dialog>

		<!--工具条 - 批量删除&分页条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination
          layout="prev, pager, next"
          :current-page="query.currentPage"
          @current-change="handleCurrentChange"
          :page-size="query.pageSize"
          :total="pageInfo.total"
          style="float:right;">
			</el-pagination>
		</el-col>

		<!--新增界面-->
    <el-dialog title="新增/修改" :visible.sync="carFormVisible" :close-on-click-modal="false">
      <el-form :model="carForm" label-width="80px"  ref="carForm">
        <el-form-item label="标题">
          <el-input v-model="carForm.title" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="封面">
          <el-upload
              class="upload-demo"
              action="http://localhost:8081/fastdfs/upload"
              :on-remove="coverHandleRemove"
              :on-success="coverHandleSuccess"
              :file-list="coverFileList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="原价">
          <el-input v-model="carForm.salePrice" style="width:220px;" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="售价">
          <el-input v-model="carForm.costPrice" style="width:220px;" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="是否新车">
          <el-radio-group v-model="carForm.isNew">
            <el-radio class="radio" :label="1">是</el-radio>
            <el-radio class="radio" :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上牌时间">
          <el-date-picker
              value-format="yyyy-MM-dd"
              v-model="carForm.registerTime"
              type="date"
              placeholder="请选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="里程数">
          <el-input v-model="carForm.mileage" style="width:220px;" type="number" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="超值">
          <el-radio-group v-model="carForm.costeffEctive">
            <el-radio class="radio" :label="1">是</el-radio>
            <el-radio class="radio" :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="急售">
          <el-radio-group v-model="carForm.rushSale">
            <el-radio class="radio" :label="1">是</el-radio>
            <el-radio class="radio" :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="准新车">
          <el-radio-group v-model="carForm.quasiNewCar">
            <el-radio class="radio" :label="1">是</el-radio>
            <el-radio class="radio" :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="可迁全国">
          <el-radio-group v-model="carForm.transitiveCountry">
            <el-radio class="radio" :label="1">是</el-radio>
            <el-radio class="radio" :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="类型">
          <el-cascader
              v-model="carForm.type"
              placeholder="试试搜索"
              :options="typeTree"
              :props="{label:'name',checkStrictly: true,value:'id'}"
              filterable
              clearable>
          </el-cascader>
        </el-form-item>
        <el-form-item label="品牌">
          <el-select v-model="carForm.brand" placeholder="请选择">
            <el-option
                v-for="item in carTypeTree"
                :key="item.value"
                :label="item.name"
                :value="item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="基本信息">
        <!--:options="quillOptions"使能够使用自己定义的富文本编辑器-->
          <quill-editor v-model="carForm.carDetail.info" :options="quillOptions">
          </quill-editor>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="carFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="save" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>
	</section>
</template>

<script>
import { quillEditor } from "vue-quill-editor"; // 调用富文本编辑器
import 'quill/dist/quill.core.css';   // 引入样式
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import quillConfig from "../../common/js/quill-config.js"  //富文本编辑器支持将图片上传到fastdfs中

	export default {
	  components:{
	    quillEditor   // 如果key和value的名字一样,可以省略 quillEditor:quillEditor
    },
		data() {
			return {
			  quillOptions:quillConfig,
				query:{
				  currentPage:1,  // 当前页
          pageSize:10,  // 每页显示条数
          keyword:""  // 关键字
        },
        pageInfo:{
				  total:0,
          rows:[]
        },
				listLoading: false,
				sels: [],//列表选中列
        
				carFormVisible: false,//新增修改界面是否显示
				carFormLoading: false,
        tableVisible: false, //显示资源抽屉
        resourceAddVisible: false, //显示资源编辑弹框
        //资源维护新增界面数据
        resourceForm:{
			    id:null,
			    carId:null,
          resourceTypeName:'',
          resourceUrlList:[]
        },
        responseUrl:[],  //将上传到fastdfs中的图片路径拼接到此数组
				carFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
        employees:[],
        carTypeTree:[],  //品牌
        sourceTree:[],  //车辆资源
        addLoading:false,
        coverFileList:[],
        resourceFileList:[], //资源维护的资源文件
        resourceFile:{   //resourceFileList中的对象，用作图片资源回显
			    name:'',
          url:''
        },
        coverFile:{
          name:'',
          url:''
        },
        carResourcesList:[],  //车辆资源
				//新增修改界面数据
        carForm: {
          id:null,
          title:"",
          cover:"",
          salePrice:0,
          costPrice:0,
          isNew:0,
          registerTime:"",
          mileage:null,
          costEffective:0,
          rushSale:0,
          quasiNewCar:0,
          transitiveCountry:0,
          type:{
            id:null,
            name:""
          },
          typeId:null,
          carDetail:{
            info:""
          },
          brand:''
        }
			}
		},
		methods: {
      resourceHandleRemove(file, fileList) {
        var filePath =file.response.data;
        this.$http.delete("/picture/delete?path="+filePath)
            .then(res=>{
              if(res.data.success){
                this.$message({
                  message: '删除成功!',
                  type: 'success'
                });
              }else{
                this.$message({
                  message: '删除失败!',
                  type: 'error'
                });
              }
            })
      },
      //文件上传
      resourceHandleSuccess(response, file, fileList){
        this.responseUrl.push(response.data);
        this.resourceForm.resourceUrlList = this.responseUrl;
      },
      //车辆资源数据提交
      resourceSave(){
        this.resourceAddVisible = false;
        this.$http.put("/carResources", this.resourceForm)
            .then(res => {
              if (res.data.success){
                this.$message.success("车辆" + this.resourceForm.carId + "资源操作成功")
                this.getCarResources(this.resourceForm.carId);  //新增资源之后再查询最新的数据
              }else {
                this.$message.error("车辆" + this.resourceForm.carId + "资源操作失败")
              }
            })
      },
      //资源删除
      resourceDel(index, row){
        this.$http.delete("/carResources/" + row.id)
            .then(res => {
              if (res.data.success){
                this.$message.success("车辆" + row.carId + "资源删除成功");
                this.getCarResources(row.carId); //删除资源之后再查询
              }else {
                this.$message.error("车辆" + row.carId + "资源删除失败");
              }
            }).catch(res => {this.$message.error(res.message)});
      },
      //资源修改
      resourceEdit(index, row){
        this.resourceAddVisible = true;
        var assign = Object.assign({}, row);
        this.resourceForm.id = row.id;
        var type = row.resourceType;
        //发送请求到后端获取资源类型名称
        this.$http.get("/carResources/resourceTypeName/" + type)
            .then(res => {
              if (res.data.code == 200){
                this.resourceForm.resourceTypeName = res.data.data;
                var resourceUrl = assign.resourceUrl;
                //有多个资源路径
                if (resourceUrl.search(',')){
                  //用逗号切割字符串，将每个路径放到resourceFileList中
                  var split = resourceUrl.split(",");
                  for (let i = 0; i < split.length; i++) {
                    var lastIndexOfUrl = split[i].lastIndexOf("/");
                    this.resourceFile.name = split[i].substring(lastIndexOfUrl + 1);  //获取文件名
                    this.resourceFile.url = split[i];  //文件路径
                    this.resourceFileList.push(this.resourceFile)
                  }
                }else {
                  //只有一个资源路径
                  var lastIndexOfUrl = resourceUrl.lastIndexOf("/");
                  this.resourceFile.name = resourceUrl.substring(lastIndexOfUrl + 1);  //获取文件名
                  this.resourceFile.url = resourceUrl;  //文件路径
                  this.resourceFileList.push(this.resourceFile)
                }
              }
            })
        //获取所有资源类型
        this.getResourceTypes();
      },
      //资源新增
      resourceAdd(){
        this.resourceAddVisible = true;
        //清空数据
        this.resourceForm = {
          resourceType:'',
          resourceUrlList:[]
        };
        this.resourceFileList = [];
        //2.调用方法获取所有资源类型
        this.getResourceTypes();
      },
      //资源维护
      maintenanceResources(index, row){
        this.tableVisible = true;
        //1.根据carId查询到对应车辆资源
        this.resourceForm.carId = row.id;
        this.getCarResources(row.id)
      },
      //获取指定车辆资源
      getCarResources(carId){
        this.$http.get("/carResources/resources/" + carId)
            .then(res => {
              if (res.data.code == 200){
                this.carResourcesList = res.data.data;
              }
            });
      },
      //获取资源类型
      getResourceTypes(){
        this.$http.post("/carResources/resourceTree")
            .then(res => {
              if (res.data.success){
                this.sourceTree = res.data.data;
                this.resourceForm.carId = this.sourceTree[0].carId
              }
            })
      },
		  // 成功回调
      coverHandleSuccess(response, file, fileList){
        this.carForm.cover = response.data;
      },
      //文件删除
      // file 当前要删除的文件  里面包含的response是后端上传接口返回的值
      // fileList 当前未被删除的所有的文件
      coverHandleRemove(file, fileList) {
        var filePath =file.response.resultObj;    // 当前要删除文件的url地址
        this.$http.delete("/fastdfs?path="+filePath)
            .then(res=>{
              if(res.data.success){
                this.$message({
                  message: '删除成功!',
                  type: 'success'
                });
                // 将shop.logo设置为null,避免将已经删除的图片的路径带到数据库
                this.carForm.cover = "";
              }else{
                this.$message({
                  message: '删除失败!',
                  type: 'error'
                });
              }
            })
      },

      search(){
        this.query.currentPage = 1;
        this.getCars();
      },
			handleCurrentChange(val) {  // val是当前页
				this.query.currentPage = val;
				this.getCars();
			},
			//获取部门列表
			getCars() {
				this.listLoading = true;  // 弹出加载框
				this.$http.post("/car",this.query)   // axios.defaults.baseURL+/car  http://localhost:80/api/car
                  .then(result => {
                    result = result.data; // 获取到后端响应回来的AjaxResult
                    if(result.success){
                       this.$message.success(result.message)
                       this.pageInfo.total = result.data.total;
                       this.pageInfo.rows = result.data.data;
                       this.listLoading = false;  // 关闭加载框
                    }else{
                      this.$message({message: '查询分页失败!'+data.message, type: 'error'});
                    }
                  })
                  .catch(result => {
                    this.$message({message: "查询分页失败!", type: 'error'});
                  })
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					this.$http.delete("/car/"+row.id)
                    .then(result => {
                       result = result.data;
                       if(result.success){
                         this.$message({message: '删除成功', type: 'success'});
                         // 刷新列表
                         this.query.currentPage = 1;
                         this.getCars();
                         this.listLoading = false;  // 关闭弹出框
                       }else{
                         this.$message({message: '删除失败!'+result.message, type: 'error'});
                       }
                    })
				}).catch(() => {
          this.$message({message: '已取消删除', type: 'info'});
				});
			},
      getEmployeeList(){
         this.$http.get("/employee")
              .then(result => {
                  result = result.data;
                  if(result.success){
                    this.employees = result.result;
                  }else{
                    this.$message({message: '获取员工列表失败!'+result.message, type: 'error'});
                  }
              }).catch(result => {
                this.$message({message: '获取员工列表失败!', type: 'error'});
              })
      },
			//显示编辑界面
			handleEdit: function (index, row) {
        //注意如果row中的对象数据为空或有数据错误会导致界面不会显示
        this.coverFile.url = row.cover;
        //http://115.159.217.249:8888/group1/M00/00/01/rBEAA2MZrEaAfCaBAAHt5Ab1hek479.jpg
        var lastIndexOfUrl = row.cover.lastIndexOf('/');
        var fileName = row.cover.substring(lastIndexOfUrl + 1);
        this.coverFile.name = fileName;
        this.coverFileList.push(this.coverFile);  //车辆图片中添加图片
				this.carFormVisible = true;
				this.carForm = Object.assign({}, row);
				if(this.carForm.type == null){
          this.carForm.type = {id:null}
        }
				if (this.carForm.carDetail == null){
				  this.carForm.carDetail = {info:''}
        }
        // 调用查询车辆类型数,渲染下拉框
        this.getCarTypeTree();
        //调用获取车辆类型属性结构，用于做级联下拉框
        this.getTypeTree();
			},
			//显示新增界面
			handleAdd: function () {
        // 弹出弹框
				this.carFormVisible = true;
				// 清空双向绑定的数据,避免将上一次填写的数据带到下一次
				this.carForm =  {
            id:null,
            title:"",
            cover:"",
            saleprice:null,
            costprice:null,
            isnew:null,
            reigstertime:"",
            mileage:null,
            costeffective:null,
            rushsale:null,
            quasinewcar:null,
            transitivecountry:null,
            type:{
              id:null,
              name:""
            },
            typeId:null,
            carDetail:{
              info:""
            },
            brand:''
        };
				// 调用查询车辆类型数,渲染下拉框
        this.getCarTypeTree();
        //调用获取车辆类型属性结构，用于做级联下拉框
        this.getTypeTree();
			},
      getTypeTree(){
        this.$http.get("/carType/treeData")
            .then(res => {
              res = res.data;
              if (res.code == 200){
                this.typeTree = res.data;
              }
            })
      },
      getCarTypeTree(){
          this.$http.get('/carType/typeTree')
              .then(result => {
                  result = result.data;
                  if(result.success){
                      this.carTypeTree = result.data;
                  }
              })
      },
			//新增修改保存方法
			save: function () {
				this.$refs.carForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.carFormLoading = true;
							let para = Object.assign({}, this.carForm);
							para.typeId = para.type.id;
							// 处理车辆类型,如果选择了车辆类型的话,它双向绑定的type是一个数组,将数组的最后一个位置的值赋值给typeId
              if(para.type && para.type.length > 0){
                para.typeId = para.type[para.type.length-1];
              }
							this.$http.put("/car",para)
                  .then(result => {
                      result = result.data;
                      if(result.success){
                        this.$message({message: '保存成功', type: 'success'});
                        this.carFormLoading = false;
                        this.query.currentPage = 1;
                        this.getCars();
                        this.carFormVisible = false;
                      }else{
                        this.$message({message: '保存失败!'+result.message, type: 'error'});
                      }
                  }).catch(result => {
                      this.$message({message: '保存失败!', type: 'error'});
                  })
						});
					}
				});
			},
      /* 处理选中的行数据，将对象转换为id */
			selsChange: function (sels) {
        var ids = sels.map(x => x.id);
				this.sels = ids;
			},
			//批量上架
			handleOnSale: function () {
				var ids = this.sels;
				this.$confirm('确定上架选中的数据吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					this.$http.post("/car/onSale", ids)
              .then((res) => {
                  if (res.data.success){
                    this.listLoading = false;
                    this.$message({
                      message: '上架成功',
                      type: 'success'
                    });
                  }else {
                    //上架失败
                    this.$message.error(res.data.message)
                  }
                  this.getCars();
					    });
				}).catch((res) => {
          this.$message.error(res.data.message)
				});
			}
		},
		mounted() { 
			this.getCars();  // 做分页查询
		}
	}

</script>

<style scoped>

</style>